//
//  TaskTeachVC.m
//  ZhiBoYuan
//
//  Created by apple on 2018/4/19.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "TaskTeachVC.h"
#import "TeachCell.h"
static NSString *ident = @"TeachCell";

#import "NewTaskVC.h"

#import "XuanKeVC.h"

#import "XuanTiViewController.h"

#import "KeChengDetailVC.h"

#import "TaoLunVC.h"



@interface TaskTeachVC ()
<
UITableViewDelegate,
UITableViewDataSource
>
@property (nonatomic, strong) NSMutableArray *dataArray;
//@property (nonatomic, strong) UITableView *tableView;
@property(nonatomic,strong)AxcEmptyDataTableView *tableView;
@property (nonatomic, assign) NSInteger pageIndex;

@property(nonatomic,assign)NSInteger visibleRow;


@end

@implementation TaskTeachVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
//    _visibleRow = 0;

    [self.view addSubview:self.tableView];

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"新建任务" style:(UIBarButtonItemStyleDone) target:self action:@selector(open)];
    
    [Helper setMoRenNav:self.navigationController];
    [Helper setNavColorFrom:self.navigationController color:ZhuTiColor];
    
    self.pageIndex = 1;
    
   [self getdate];

}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)getdate {
    
    SGParameter *parameter  = [[SGParameter alloc] init];
    
    
    NSLog(@"%ld",self.pageIndex);
    
    parameter.body = @{@"page":[NSString stringWithFormat:@"%ld",self.pageIndex],
                       @"page_count":@"10" };
    
    NSString *lastUrl  = @"g=Client&m=Task&a=taskList";
    __weak __typeof(&*self)weakSelf = self;
    [SGHttpTool POST:[NSString stringWithFormat:@"%@%@",HTTPP,lastUrl] parameter:parameter sucess:^(id responseObject) {
        
        NSDictionary *dic = responseObject;
        
        NSMutableArray *arr = dic[@"data"][@"task_list"];
        
        NSLog(@"任务列表 = %@",arr);
    
        
        [weakSelf updatePagesData:arr page:weakSelf.pageIndex];
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        
    }];
}

#pragma mark ————————— 分页加载数据 —————————————

- (void)updatePagesData:(NSArray*)newData page:(NSInteger)pageIdx {
    
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];

    if ( newData == nil || newData.count <= 0 )  {  return; }
    
    self.pageIndex = pageIdx;
    
    if ( pageIdx == 1 )
    {
        [self.dataArray removeAllObjects];
        self.dataArray = [NSMutableArray arrayWithArray:newData];
    }
    else
    {
        [self.dataArray addObjectsFromArray:newData];
        
    }
    NSLog(@"刷新数据");
    

    
    [self.tableView reloadData];
//    if (self.dataArray.count > _visibleRow)
//    {
//        [self.tableView scrollToRow:0 inSection:_visibleRow atScrollPosition:(UITableViewScrollPositionTop) animated:YES];
//    }
    
}

#pragma mark -----------------------新建任务 ------------------------
- (void)open {
    NSLog(@"新建任务");
    
    NewTaskVC *vc = [[NewTaskVC alloc]init];
     __weak __typeof(&*self)weakSelf = self;
    
    
    vc.fresh = ^(Task *task ){
        weakSelf.pageIndex =1;
        
        if (weakSelf.dataArray.count>0)
        {
           [weakSelf.tableView scrollToRow:0 inSection:0 atScrollPosition:(UITableViewScrollPositionTop) animated:YES];
        }

        [weakSelf getdate];
    };
    
    vc.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:vc animated:YES];
}




-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    NSIndexPath *indexpath = [self.tableView indexPathForCell:[self.tableView.visibleCells firstObject]];
    
    _visibleRow = indexpath.row;
    
    NSLog(@"sdfsfdff = %zd",indexpath.row);
}


//-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
//    return 1;
//}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    TeachCell *cell = [tableView dequeueReusableCellWithIdentifier:ident forIndexPath:indexPath];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor clearColor];

    Task *t = [[Task alloc]initWithDictionary:self.dataArray[indexPath.row]];
    cell.task = t;
    
    
    NSLog(@"t.status ==  %@",t.status);
    
    
    
    BTN_MSG_FUNC(cell.aButton, xuanKeSender:);
    BTN_MSG_FUNC(cell.bButton, xuanTiSender:);
    BTN_MSG_FUNC(cell.cButton, faBuSender:);
    BTN_MSG_FUNC(cell.dButton, bianJiiSender:);
    BTN_MSG_FUNC(cell.eButton, shanChuSender:);
    
    BTN_MSG_FUNC(cell.pingLunButton, pingLunSender:);

    return cell;
}
#pragma mark ----------------------- 讨论 ------------------------
-(void)pingLunSender:(UIButton *)sender{
    
    NSIndexPath *myIndex=[self.tableView indexPathForCell:(TeachCell*)[[sender superview]superview]];
    //如果按钮是加在cell上的contentView上
//    NSLog(@"myIndex.section==%ld",myIndex.section);
//    NSLog(@"myIndex.row==%ld",myIndex.row);
    
    
    Task *t = [[Task alloc]initWithDictionary:self.dataArray[myIndex.row]];
    
    TaoLunVC *vc = [[TaoLunVC alloc]init];
    
    vc.course_id = t.id;
    
    vc.task =t;
    
    vc.fresh = ^(Task *task) {
        
        
        [self.dataArray replaceObjectAtIndex:myIndex.row withObject: t.mj_keyValues];
        NSIndexPath *indexPathA = [NSIndexPath indexPathForRow:myIndex.row inSection:myIndex.section];
        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPathA,nil] withRowAnimation:UITableViewRowAnimationNone];
        
    };

    
    
    
    vc.hidesBottomBarWhenPushed =YES;
    
    
    [self.navigationController pushViewController:vc animated:YES];
    
    
    
    NSLog(@"评论评论评论评论");//讨论-2

}
#pragma mark -----------------------选课------------------------
-(void)xuanKeSender:(UIButton *)sender{
    
    
    NSIndexPath *myIndex=[self.tableView indexPathForCell:(TeachCell*)[[sender superview]superview]];
    //如果按钮是加在cell上的contentView上
    NSLog(@"myIndex.section==%ld",myIndex.section);
    NSLog(@"myIndex.row==%ld",myIndex.row);
    
    NSLog(@"选课");
    
    
    XuanKeVC *vc = [[XuanKeVC alloc]init];
    
    Task *t = [[Task alloc]initWithDictionary:self.dataArray[myIndex.row]];
    
    vc.teskID = t.id;
    vc.task =t;
    
    vc.fresh = ^(Task *task) {

        
        [self.dataArray replaceObjectAtIndex:myIndex.row withObject: t.mj_keyValues];
        NSIndexPath *indexPathA = [NSIndexPath indexPathForRow:myIndex.row inSection:myIndex.section];
        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPathA,nil] withRowAnimation:UITableViewRowAnimationNone];
        
    };

    
    vc.hidesBottomBarWhenPushed =YES;
    
    [self.navigationController pushViewController:vc animated:YES];
    
    

    
}
#pragma mark -----------------------选题------------------------
-(void)xuanTiSender:(UIButton *)sender{
    
    NSIndexPath *myIndex=[self.tableView indexPathForCell:(TeachCell*)[[sender superview]superview]];
    //如果按钮是加在cell上的contentView上
    NSLog(@"myIndex.section==%ld",myIndex.section);
    NSLog(@"myIndex.row==%ld",myIndex.row);
    NSLog(@"选题");
    
    
    XuanTiViewController *vc = [[XuanTiViewController alloc]init];
    
    
    Task *t = [[Task alloc]initWithDictionary:self.dataArray[myIndex.row]];
    
    vc.teskID = t.id;
    vc.task = t;
    
    

    vc.fresh = ^(Task *task) {



        [self.dataArray replaceObjectAtIndex:myIndex.row withObject: t.mj_keyValues];
        NSIndexPath *indexPathA = [NSIndexPath indexPathForRow:myIndex.row inSection:myIndex.section];
        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPathA,nil] withRowAnimation:UITableViewRowAnimationNone];
        
    };

    
    

    vc.hidesBottomBarWhenPushed =YES;
    
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark -----------------------发布------------------------
-(void)faBuSender:(UIButton *)sender{
    NSIndexPath *myIndex=[self.tableView indexPathForCell:(TeachCell*)[[sender superview]superview]];
    //如果按钮是加在cell上的contentView上
    NSLog(@"myIndex.section==%ld",myIndex.section);
    NSLog(@"myIndex.row==%ld",myIndex.row);
    NSLog(@"发布");
    
    
    
    SGParameter *parameter  = [[SGParameter alloc] init];
    
    Task *t = [[Task alloc]initWithDictionary:self.dataArray[myIndex.row]];
    

    
    parameter.body = @{@"task_id": t.id };
    NSString *lastUrl  = @"g=Client&m=Task&a=publishTask";
//    __weak __typeof(&*self)weakSelf = self;
    [SGHttpTool POST:[NSString stringWithFormat:@"%@%@",HTTPP,lastUrl] parameter:parameter sucess:^(id responseObject) {
        
        NSDictionary *dic = responseObject;
        
//        NSMutableArray *arr = dic[@"data"][@"task_list"];
        
        NNSLog(@"%@",dic);
        
        if ([dic[@"status"] integerValue] == 200)
        {
            
                t.status = @"1";
                [self.dataArray replaceObjectAtIndex:myIndex.row withObject:t.mj_keyValues];
                NSIndexPath *indexPathA = [NSIndexPath indexPathForRow:myIndex.row inSection:myIndex.section];
                [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPathA,nil] withRowAnimation:UITableViewRowAnimationNone];

            
        }
        else
        {
             [MBProgressHUD showTextOnly:self.view message:dic[@"msg"] delay:3];
        }
        
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        
    }];
    
    
    
    
}


#pragma mark -----------------------编辑------------------------
-(void)bianJiiSender:(UIButton *)sender{
    NSIndexPath *myIndex=[self.tableView indexPathForCell:(TeachCell*)[[sender superview]superview]];
    //如果按钮是加在cell上的contentView上
    NSLog(@"myIndex.section==%ld",myIndex.section);
    NSLog(@"myIndex.row==%ld",myIndex.row);
      NSLog(@"编辑");
    
    
    
    Task *t = [[Task alloc]initWithDictionary:self.dataArray[myIndex.row]];
    NewTaskVC *vc = [[NewTaskVC alloc]init];
    vc.task = t;
    vc.fresh = ^(Task *task) {
        

        
        [self.dataArray replaceObjectAtIndex:myIndex.row withObject: t.mj_keyValues];
        NSIndexPath *indexPathA = [NSIndexPath indexPathForRow:myIndex.row inSection:myIndex.section];
        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPathA,nil] withRowAnimation:UITableViewRowAnimationNone];
        
    };
    
    vc.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:vc animated:YES];
    
    
    
    
}

#pragma mark -----------------------删除------------------------
-(void)shanChuSender:(UIButton *)sender{
    NSIndexPath *myIndex=[self.tableView indexPathForCell:(TeachCell*)[[sender superview]superview]];
    //如果按钮是加在cell上的contentView上
    NSLog(@"myIndex.section==%ld",myIndex.section);
    NSLog(@"myIndex.row==%ld",myIndex.row);
     NSLog(@"删除");
    
//    CGPoint point = sender.center;
//    point = [self.tableView convertPoint:point fromView:sender.superview];
//    NSIndexPath* myIndex = [self.tableView indexPathForRowAtPoint:point];
//    NSLog(@"%ld",(long)myIndex.row);
    
    
    
    
    SGParameter *parameter  = [[SGParameter alloc] init];
    Task *t = [[Task alloc]initWithDictionary:self.dataArray[myIndex.row]];
    
    
    parameter.body = @{@"task_id":t.id };
    
    NSString *lastUrl  = @"g=Client&m=Task&a=delTask";
    __weak __typeof(&*self)weakSelf = self;
    [SGHttpTool POST:[NSString stringWithFormat:@"%@%@",HTTPP,lastUrl] parameter:parameter sucess:^(id responseObject) {
        
        NSDictionary *dic = responseObject;
        
        NSString *str = dic[@"status"];
        
        NNSLog(@"%@",dic);
        
        if ([str integerValue] == 200)
        {
            [self.dataArray removeObjectAtIndex:myIndex.row];
            
             [self.tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:myIndex.row inSection:0]] withRowAnimation:UITableViewRowAnimationTop];

        }else{
            [MBProgressHUD showTextOnly:weakSelf.view message:dic[@"msg"] delay:3];
        }
        
        
//        [weakSelf updatePagesData:arr page:weakSelf.pageIndex];
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        
    }];
}

-(NSMutableArray *)dataArray
{
    if (!_dataArray)
    {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (AxcEmptyDataTableView *)tableView {
    if (!_tableView) {
        AxcEmptyDataTableView *  tableView = [[AxcEmptyDataTableView alloc] initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT, ScreenWidth, Screenheight- NAVIGATION_BAR_HEIGHT -TAB_BAR_HEIGHT) style:UITableViewStylePlain];
        tableView.backgroundColor = [UIColor clearColor];
        tableView.delegate        = self;
        tableView.dataSource      = self;
        tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
        
        tableView.estimatedRowHeight = 44.0f;//推测高度，必须有，可以随便写多少
        
        tableView.rowHeight = UITableViewAutomaticDimension;//iOS8之后默认就是这个值，可以省略
        
        
        
        tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        
        //        self.extendedLayoutIncludesOpaqueBars = YES;
        
        if (@available(iOS 11.0, *)) {
            tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        //        if (iPhoneX) {
        //            tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        //            tableView.scrollIndicatorInsets = _tableView.contentInset;
        //        }
        
        
        
        [tableView registerNib:[UINib nibWithNibName:ident bundle:nil] forCellReuseIdentifier:ident];
        
        [tableView setTableFooterView:[[UIView alloc] initWithFrame:CGRectZero]];
        __weak __typeof(&*self)weakSelf = self;
        
        // 下拉刷新
        tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            
            weakSelf.pageIndex = 1;
            
            [weakSelf getdate];
            
            
        }];
        
        
        //         上拉加载
        tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            
            if ( weakSelf.pageIndex < -1 )
            {
                weakSelf.pageIndex = 1;
            }
            weakSelf.pageIndex++;
            [weakSelf getdate];
            
        }];
        
        self.placeholderView.frame = tableView.bounds;
        
        // 设置空集时候展示的View
        tableView.axcUI_placeHolderView = self.placeholderView;
        
        //  默认YES 自带渐入渐出动画效果，下边这个参数可以关闭
        tableView.axcUI_placeHolderViewAnimations = NO;
        
        // 占位View的“重新加载”按钮的Block回调:
        __weak typeof(self) WeakSelf = self;
        
        self.placeholderView.clickLoadBtnBlock = ^(id type) {
            //        WeakSelf.dataArray = nil;
            
            
//            [WeakSelf downloadHomePageDatas];
            
            WeakSelf.pageIndex = 1;
            
            [WeakSelf getdate];
            
        };
        
        
        _tableView = tableView;
        
    }
    return _tableView;
}








- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
